﻿using System.IO;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Fee.FileAttachs;
using Fee.IO.Importers;
using Identity;
using Identity.ViewModels;
using JwtWebApi.Data;
using JwtWebApi.Filters;
using JwtWebApi.Models.Manage;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace JwtWebApi.Controllers.Manage
{
    [Authorize]
    [Route("manage/[controller]")]
    [ApiController]
    [EnableCors]
    public class VendorController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly FileManager _fileManager;
        private readonly UserManager<User> _userManager;

        public VendorController(ApplicationDbContext context, UserManager<User> userManager, FileManager fileManager)
        {
            _context = context;
            _userManager = userManager;
            _fileManager = fileManager;
        }

        [HttpGet("list")]
        public IActionResult Index([FromQuery] VendorSearcher searcher)
        {
            var query = _context.Vendors;
            if (!string.IsNullOrEmpty(searcher.Name))
                query = query.Where(f => f.Name.Contains(searcher.Name) || f.FullName.Contains(searcher.Name));


            return Json(new
            {
                data = query.Skip(searcher.GetSkip()).Take(searcher.GetTake()),
                total = query.Count()
            });
        }

        [HttpGet("list-simple")]
        public IActionResult ListSimple([FromQuery] VendorSearcher searcher)
        {
            var query = _context.Vendors;

            var row = query.Take(searcher.PageSize ?? 1).Skip(searcher.GetSkip()).Select(f =>
                new VendorSimpleViewModel
                {
                    Name = f.Name,
                    Id = f.Id
                });
            return Json(new
            {
                data = row,
                total = query.Count()
            });
        }


        [HttpPost("Save")]
        [ModelValidteFilter]
        public IActionResult Save([FromBody] VendorDetailViewModel vendorDetailViewModel)
        {
            var vendor = Mapper.Map<Vendor>(vendorDetailViewModel);
            if (vendor.Id != 0)
                _context.Update(vendor);
            else
                _context.Add(vendor);

            _context.SaveChanges();
            return Json(new {successed = true, message = "成功"});
        }

        [HttpGet("get/{id}")]
        public IActionResult Get(int id)
        {
            var district = _context.Vendors
                .FirstOrDefault(_ => _.Id == id);
            return Json(district);
        }

        [HttpPost("Import")]
        public async Task<IActionResult> Post([FromForm] IFormFile formFile, [FromRoute] string type)
        {
            // full path to file in temp location
            var filePath = _fileManager.GetTempPrivateFile(Path.GetExtension(formFile.FileName), User.Identity);
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }

            var manager = new VendorImporter<ApplicationDbContext>(_context, _userManager);

            var isValidate = manager.Import(filePath, out var rowResults, out var resultFilePath);
            var message = isValidate ? "导入成功" : "导入失败";
            message += "。请点击结果文件，查看文件导入结果";

            return Json(new
            {
                successed = isValidate,
                resultFilePath,
                message
            });
        }
    }
}